<template>
  <div class="tool-item flex flex-col overflow-hidden tool-dom"
    :data-handle="toolsData.handle"
    :data-advertisement_id="toolsData.advertisement_id ? toolsData.advertisement_id : ''"
    :data-position="toolPosition"
    :data-index="toolPosIndex"
    :class="{'history-recommended': hasRealVal(toolsData.is_noticeable) && toolsData.is_noticeable === 1}">
    <a :href="toolsData.website"
      @click="handleExp(0, toolsData)"
      rel="dofollow"
      v-if="(hasRealVal(toolsData.is_recommend_now) && toolsData.is_recommend_now) || hasRealVal(toolsData.advertisement_id)"
      target="_blank"
      class="flex-shrink-0 tool-linear tool-linear go-tool-detail-pic">
      <div class="flex tool-pic items-center justify-center skeleton-bg">
        <common-image class="w-full h-full flex-shrink-0"
          :src="toolsData.image"
          :alt="toolName"
          :lazy="toolPosIndex && toolPosIndex > 2 ? true : false"></common-image>
      </div>
    </a>
    <common-link path="/tool/:handle"
      @click.native="handleExp(0, toolsData)"
      v-else
      target="_blank"
      :params="{ handle: toolsData.handle}"
      class="flex-shrink-0 tool-linear tool-linear go-tool-detail-pic">
      <div class="flex tool-pic items-center justify-center skeleton-bg">
        <common-image class="w-full h-full flex-shrink-0"
          :src="toolsData.image"
          :alt="toolName"
          :lazy="toolPosIndex && toolPosIndex > 2 ? true : false"></common-image>
      </div>
    </common-link>
    <div class="flex-1 bg-white px-4 pt-3 pb-4 flex flex-col justify-between relative">
      <div class="flex-1 block">
        <div class="flex items-center justify-between">
          <div class="block flex-1 w-0 fs0">
            <div class="relative fs0 inline-block max-w-full">
              <a :href="toolsData.website"
                @click="handleExp(1, toolsData)"
                rel="dofollow"
                v-if="(hasRealVal(toolsData.is_recommend_now) && toolsData.is_recommend_now) || hasRealVal(toolsData.advertisement_id)"
                target="_blank"
                class="max-w-full inline-block go-tool-detail-name">
                <div class="text-xl font-semibold text-gray-1000 flex-1 truncate break-words hover:text-purple-1300"
                  :title="toolName">
                  {{ toolName }}
                </div>
              </a>
              <common-link path="/tool/:handle"
                v-else
                @click.native="handleExp(1, toolsData)"
                target="_blank"
                :params="{ handle: toolsData.handle}"
                class="max-w-full inline-block go-tool-detail-name">
                <div class="text-xl font-semibold text-gray-1000 flex-1 truncate break-words hover:text-purple-1300"
                  :title="toolName">
                  {{ toolName }}
                </div>
              </common-link>
            </div>
          </div>
          <a :href="toolsData.website"
            @click="handleExp(2, toolsData)"
            :rel="hasRealVal(toolsData.is_noticeable) && toolsData.is_noticeable === 1 ? 'dofollow' : 'nofollow'"
            class="flex items-center flex-shrink-0 ml-3 group"
            v-if="hasRealVal(toolsData.website)"
            target="_blank">
            <svg-icon className="text-base text-gray-1500 group-hover:text-purple-1300"
              iconName='openTool'></svg-icon>
          </a>
        </div>
        <div class="flex-shrink-0 flex items-center justify-between mt-3">
          <div class="flex-1 flex items-center">
            <div class="flex-shrink-0 flex items-center"
              :title="$t('monthlyVisits')">
              <div class="w-3 h-3">
                <svg-icon className="text-xs mt--2"
                  iconName='similarweb'></svg-icon>
              </div>
              <span class="ml-1.5 text-xs text-gray-1000">{{toolsData.month_visited_count | vResetVisit}}</span>
            </div>

            <div class="flex-shrink-0 flex items-center flag ml-3"
              v-if="toolsData.traffic && (toolsData.traffic.top_region || toolsData.traffic.top_region_value)"
              :title="getTitle()">
              <img :src="getImage(toolsData.traffic.top_region)"
                alt=""
                srcset=""
                v-if="toolsData.traffic.top_region">
              <span class="text-xs text-gray-1000 ml-1.5"
                v-if="toolsData.traffic.top_region_value">{{(toolsData.traffic.top_region_value * 100).toFixed(2)}}%</span>
            </div>
          </div>

          <div class="flex items-center flex-shrink-0 ml-3 -mt-0.5 group text-gray-1300 cursor-pointer hover:text-purple-1300 group to-add-or-cancle-favorites"
            :class="{'text-purple-1300': toolsData.user_collected}"
            @click="addOrCancleFavorites()">
            <svg-icon className="text-md -mt-1"
              iconName='star_filled'
              v-if="!loading"></svg-icon>
            <img :src="loadingSrc"
              class="loading h-4 w-4"
              alt=""
              srcset=""
              v-if="loading">
            <span class="ml-2 text-md text-gray-1000 group-hover:text-purple-1300">{{toolsData.collected_count | vReset}}</span>
          </div>
        </div>
        <div class="mt-2.5 text-sm text-gray-1500 break-words tool-desc leading-6 go-tool-detail-description"
          :title="toolsData.description">
          {{toolsData.description}}
        </div>
      </div>
      <div class="flex items-start flex-wrap flex-shrink-0 mt-1 gap-x-3 gap-y-3 maxHeight overflow-hidden relative"
        :class="{'relative h-6 pr-8': toolsData.is_ad}"
        v-if="!isHideCategories && ((toolsData.categories && toolsData.categories.length > 0) || toolsData.is_ad)">
        <template v-for="(tItem, tKey) in toolsData.categories">
          <common-link path="/category/:handle"
            v-if="((!specialHandle && tKey < 3) || (specialHandle && specialHandle === tItem.handle))"
            :params='{handle:tItem.handle }'
            class="text-xs text-purple-1700 border border-purple-1500 bg-purple-1600 max-w-max truncate rounded-2xl t-label hover:bg-purple-1300 hover:text-white go-category-link"
            :key="tKey">{{tItem.name}}</common-link>
        </template>
      </div>
      <slot name="extra"></slot>
      <div class="absolute right-4 bottom-4 border bg-gray-2600 border-gray-3100 text-xs leading-none text-gray-1000 w-6 h-6 flex items-center justify-center rounded-full"
        v-if="toolsData.is_ad">
        {{$t('common_ad')}}
      </div>
    </div>
  </div>
</template>

<script>
import mixinsExposure from '~/mixins/mixins-exposure'
import _ from 'lodash'
import { mapState, mapActions } from 'vuex'
export default {
  name: 'MinTools',
  props: {
    toolsData: {
      type: Object,
      default: {},
    },
    //仅展示特定分类
    specialHandle: {
      type: String | null,
      default: null,
    },
    isHideCategories: {
      type: Boolean,
      default: false,
    },
    toolPosition: {
      type: String,
      default: 'Featured',
    },
    toolPosIndex: {
      type: Number,
      default: 1,
    },
  },
  mixins: [mixinsExposure],
  data() {
    return {
      loading: false,
      loadingSrc: require('@/static/images/loading.png'),
    }
  },
  watch: {
    toolsData: {
      handler() {
        if (this.toolsData && this.toolsData.image) {
          let iSrc = this.toolsData.image
          if (iSrc.indexOf('x-oss-process') === -1) {
            iSrc = `${iSrc}${
              iSrc.indexOf('?') === -1 ? '?' : '&'
            }x-oss-process=image/resize,l_600,m_lfit`
          }
          if (
            iSrc.indexOf('https://nav-station.oss-accelerate.aliyuncs.com') >= 0
          ) {
            iSrc = iSrc.replace(
              'https://nav-station.oss-accelerate.aliyuncs.com',
              'https://cdn-images.toolify.ai'
            )
          }
          this.toolsData.image = iSrc
        }
      },
      deep: true,
      immediate: true,
    },
  },
  computed: {
    ...mapState({
      locale: (state) => state.locale,
      countries: (state) => state.countries,
    }),
    //标签详情页描述由一句话以及原描述组成
    description() {
      let isTag = this.$route.name === 'tag' || this.$route.name === 'lang-tag'
      if (isTag) {
        return `${toolsData.what_is_summary ? toolsData.what_is_summary : ''}${
          toolsData.description ? toolsData.description : ''
        }`
      } else {
        return toolsData.description ? toolsData.description : ''
      }
    },
    toolName() {
      return this.$websiteName(this.toolsData)
    },
  },
  filters: {
    vReset: function (val) {
      if (typeof val === 'number' && !isNaN(val)) {
        if (val <= 1000) {
          return val
        } else if (val > 1000 && val < 1000000) {
          return (val / 1000).toFixed(1) + 'K'
        } else if (val >= 1000000 && val < 1000000000) {
          return (val / 1000000).toFixed(1) + 'M'
        } else {
          return (val / 1000000000).toFixed(1) + 'B'
        }
      } else {
        return val ? val : 0
      }
    },
    vResetVisit: function (val) {
      if (typeof val === 'number' && !isNaN(val)) {
        if (val < 5000) {
          return '< 5K'
        } else if (val >= 5000 && val < 1000000) {
          return (val / 1000).toFixed(1) + 'K'
        } else if (val >= 1000000 && val < 1000000000) {
          return (val / 1000000).toFixed(1) + 'M'
        } else {
          return (val / 1000000000).toFixed(1) + 'B'
        }
      } else {
        return '< 5K'
      }
    },
  },
  methods: {
    ...mapActions(['exposure']),
    async addOrCancleFavorites() {
      this.loading = true
      try {
        try {
          let res

          switch (this.toolsData.user_collected) {
            case 0:
              res = await this.$axiosApi.postFavorites({
                handle: this.toolsData.handle,
              })
              break
            case 1:
              res = await this.$axiosApi.deleteFavorites({
                handle: this.toolsData.handle,
              })
              break
            default:
              console.log('error')
          }

          this.loading = false
          if (res && res.code === 200) {
            this.$message.success(
              this.toolsData.user_collected
                ? this.$i18n.t('cancelFavoritesSuccess')
                : this.$i18n.t('addFavoritesSuccess')
            )
            this.toolsData.collected_count = this.toolsData.user_collected
              ? parseInt(this.toolsData.collected_count) - 1
              : parseInt(this.toolsData.collected_count) + 1
            this.toolsData.user_collected = this.toolsData.user_collected
              ? 0
              : 1

            this.$emit('updateData', this.toolsData.handle)
          }
        } catch (error) {
          this.loading = false
          console.log(error)
        }
      } catch (error) {}
    },
    //判断是否有国旗
    getImage(name) {
      try {
        const image = require('@/static/images/flags/' + name + '.png')
        if (image) {
          return image
        } else {
          return ''
        }
      } catch (error) {
        //console.log(error)
      }
    },
    getTitle() {
      let targetCountry = this.countries.find((item) => {
        return item.value === this.toolsData.traffic.top_region
      })
      let percent = `${(this.toolsData.traffic.top_region_value * 100).toFixed(
        2
      )}%`

      return `${
        targetCountry && targetCountry.label
          ? targetCountry.label
          : this.toolsData.traffic.top_region
      }: ${percent}`
    },
    getLocaleText(val, val_locales) {
      if (
        Object.prototype.toString.call(val_locales) === '[object Object]' &&
        typeof val_locales[this.locale] != 'undefined' &&
        val_locales[this.locale] !== null &&
        val_locales[this.locale] !== ''
      ) {
        return val_locales[this.locale]
      } else {
        return val
      }
    },

    handleExp(key = 0, toolsData) {
      this.getThrottledClickFunction(toolsData, key)()
    },
    getThrottledClickFunction(toolsData, key) {
      let functionKey = `${toolsData.handle}-${key}`
      if (!this.throttledClickFunctions[functionKey]) {
        this.throttledClickFunctions[functionKey] = _.throttle(() => {
          let exporeData = this.getExporeData(
            toolsData,
            this.toolPosition,
            this.toolPosIndex,
            false
          )
          this.exposure({
            ...exporeData,
          })
        }, 2000) // 设置节流时间间隔
      }
      return this.throttledClickFunctions[functionKey]
    },
  },
}
</script>
<style lang='scss' scoped>
.tool-item {
  border-radius: 11px;
  box-shadow: 0px 4px 6px 0px rgba(0, 0, 0, 0.08);
  &.history-recommended {
    border: 2px solid rgba(169, 176, 255, 1);
  }
  overflow: hidden;
  .tool-desc {
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
  }

  .tool-linear {
    .tool-pic {
      width: 100%;
      aspect-ratio: 137 / 85;
      overflow: hidden;
    }
  }

  .tool-linear {
    .tool-pic {
      border-radius: 10px 10px 0px 0px;
      width: 100%;
      aspect-ratio: 137 / 85;
      overflow: hidden;
    }
  }

  .tool-pic {
    img {
      border-radius: 10px 10px 0 0;
    }
  }

  .t-label {
    padding: 3px 10px;
  }

  .flag {
    margin-top: -1px;
    img {
      width: 14px;
      height: 10px;
    }
  }
  .maxHeight {
    max-height: 24px;
  }
}
</style>
